package com.masterclient.app.businessmodule.usermodule.userinfo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.user.callback.UserDataCallBack;
import com.eoner.middlelib.router.intercept.FCBaseIntercept;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.eoner.uikit.dialog.simple.ChooseHeadImgDialog;
import com.masterclient.app.businessmodule.minemodule.address.AddressSelectDialog;
import com.eoner.baselibrary.bean.address.AddressListBean;
import com.eoner.baselibrary.bean.address.City;
import com.eoner.commonbean.user.CustomerBean;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.masterclient.app.businessmodule.usermodule.userinfo.contract.UserInfoContract;
import com.masterclient.app.businessmodule.usermodule.userinfo.contract.UserInfoPresenter;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;
import top.zibin.luban.Luban;

import static com.masterclient.app.R.id.rl_gender;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UpdateNameActivity.RESULRCODE;

/**
 * 作者：sean
 * 创建时间：2017/7/14 10:18
 * 功能说明：
 */
@Route(path = FCRouterPath.USER_PERSONAL_PATH)
public class UserInfoActivity extends FCBusinessActivity<UserInfoPresenter> implements UserInfoContract.View {
    @BindView(R.id.iv_user_head)
    ImageView ivUserHead;
    @BindView(R.id.rl_user_head)
    RelativeLayout rlUserHead;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.rl_nick)
    RelativeLayout rlNick;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(rl_gender)
    RelativeLayout rlGender;
    @BindView(R.id.tv_birth)
    TextView tvBirth;
    @BindView(R.id.rl_birth)
    RelativeLayout rlBirth;
    @BindView(R.id.tv_live_place)
    TextView tvLivePlace;
    @BindView(R.id.rl_live_place)
    RelativeLayout rlLivePlace;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_invite_nickname)
    TextView tvInviteNickname;
    @BindView(R.id.tv_invite_phone)
    TextView tvInvitePhone;
    @BindView(R.id.tv_signature)
    TextView tvSignature;

    private ChooseHeadImgDialog headImgDialog;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int IMAGE_PICKER = 102;

    private AddressSelectDialog dialog;
    private String mPositon = "3";
    String cityId, provinceId, area_id,fromType;
    String address1, address2, address3;
    RxPermissions rxPermissions;

    private CustomerBean mCustomerBean;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("个人信息");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        fromType = getIntent().getStringExtra("user_type");

        rxPermissions = new RxPermissions(UserInfoActivity.this);
        headImgDialog = new ChooseHeadImgDialog(this, "修改头像", "相册", "拍照");
        headImgDialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
            @Override
            public void album() {
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(UserInfoActivity.this, "开启相册权限", "上传头像需要从相册上传权限，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_storage, () -> {
                        Intent intent = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent, IMAGE_PICKER);
                    }).show();
                }else {
                    Intent intent = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, IMAGE_PICKER);
                }
            }

            @Override
            public void photo() {
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(UserInfoActivity.this, "开启摄像头、相册权限", "拍摄头像需要相机、相册权限，请在下一个页面点击“允许”",
                            R.mipmap.icon_permission_phone, () -> requestPermissions()).show();
                }else {
                    Intent intent = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                    startActivityForResult(intent, REQUEST_CODE_SELECT);
                }
            }
        });

        if ("head".equals(fromType)){ headImgDialog.show();}
        UserDataManager.getInstance().requestCustomerInfoForceUpdate(new UserDataCallBack() {
            @Override
            public void onSuccess(CustomerBean customerBean) {
                mCustomerBean = customerBean;
                showUserInfo(customerBean);
            }
        });
    }

    private void requestPermissions(){
        rxPermissions
                .request(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(@NonNull Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    Intent intent = new Intent(UserInfoActivity.this, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                    startActivityForResult(intent, REQUEST_CODE_SELECT);
                } else {
                    Toast.makeText(UserInfoActivity.this, "文件权限或照相机权限申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showUserInfo(CustomerBean customerBean) {

        tvPhone.setText(UserDataManager.getInstance().getMobile());
        tvInviteNickname.setText(customerBean.getData().getInvite_nick_name());
        tvInvitePhone.setText(customerBean.getData().getInvite_mobile());

        ViewTransformUtil.glideImageView(this,UserDataManager.getInstance().getHeadImgUrl(),ivUserHead,
                new CropCircleWithBorderTransformation(0,0x0A3D2529), R.mipmap.user_head_default_icon);

        tvNick.setText(UserDataManager.getInstance().getNickName());

        if ("0".equals(customerBean.getData().getSex())) {
            tvGender.setText("保密");
        } else if ("1".equals(customerBean.getData().getSex())) {
            tvGender.setText("男");
        } else if ("2".equals(customerBean.getData().getSex())) {
            tvGender.setText("女");
        }

        String area = "";
        if (!TextUtils.isEmpty(customerBean.getData().getProvince_name())) {
            area += (" " + customerBean.getData().getProvince_name());
        }

        if (!TextUtils.isEmpty(customerBean.getData().getCity_name())) {
            area += (" " + customerBean.getData().getCity_name());
        }

        if (!TextUtils.isEmpty(customerBean.getData().getArea_name())) {
            area += (" " + customerBean.getData().getArea_name());
        }
        if (TextUtils.isEmpty(area)) {
            tvLivePlace.setText("未填写");
            tvLivePlace.setTextColor(Color.parseColor("#999999"));
        } else {
            tvLivePlace.setText(area);
            tvLivePlace.setTextColor(Color.parseColor("#999999"));
        }


        if (!TextUtils.isEmpty(customerBean.getData().getIntroduce())) {
            tvSignature.setText(customerBean.getData().getIntroduce());
            tvSignature.setTextColor(Color.parseColor("#999999"));
        } else {
            tvSignature.setText("未填写");
            tvSignature.setTextColor(Color.parseColor("#999999"));
        }

        if (TextUtils.isEmpty(customerBean.getData().getBirthday())) {
            tvBirth.setText("未填写");
            tvBirth.setTextColor(Color.parseColor("#999999"));
        } else {
            tvBirth.setText(customerBean.getData().getBirthday());
            tvBirth.setTextColor(Color.parseColor("#999999"));
        }
    }

    @OnClick({R.id.signature_layout,R.id.rl_user_head, R.id.rl_nick, R.id.rl_birth, R.id.rl_live_place, R.id.rl_gender,R.id.phone_layout})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.signature_layout:
                if (mCustomerBean!=null && mCustomerBean.getData() != null && mCustomerBean.getData().getIntroduce() != null) {
                    ARouter.getInstance().build(FCRouterPath.USER_SIGNATURE)
                            .withString("content",mCustomerBean.getData().getIntroduce()).navigation(this,0x57);
                } else {
                    ARouter.getInstance().build(FCRouterPath.USER_SIGNATURE)
                            .withString("content","").navigation(this,0x57);
                }

                break;
            case R.id.rl_user_head:
                headImgDialog.show();
                break;
            case R.id.rl_nick:
                ARouter.getInstance().build(FCRouterPath.USER_MODIFY_NICK_NAME).navigation(UserInfoActivity.this,100,new FCBaseIntercept());
                break;
            case rl_gender:
                ChooseHeadImgDialog dialog = new ChooseHeadImgDialog(UserInfoActivity.this, "选择性别", "男", "女");
                dialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
                    @Override
                    public void album() {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("gender", "1");
                        mPresenter.updateUserInfo(map);
                        dialog.dismiss();
                    }

                    @Override
                    public void photo() {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("gender", "2");
                        mPresenter.updateUserInfo(map);
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.rl_birth:
                String birthDay = "";
                if (mCustomerBean!=null && mCustomerBean.getData() != null && mCustomerBean.getData().getBirthday() != null) {
                    birthDay = mCustomerBean.getData().getBirthday();
                }
                DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(UserInfoActivity.this, new DatePickerPopWin.OnDatePickedListener() {
                    @Override
                    public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
//                        Toast.makeText(mContext, dateDesc, Toast.LENGTH_SHORT).show();
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("birthday", dateDesc);
                        mPresenter.updateUserInfo(map);
                    }
                }).textConfirm("确定") //text of confirm button
                        .textCancel("取消") //text of cancel button
                        .btnTextSize(16) // button text size
                        .viewTextSize(16) // pick view text size
                        .colorCancel(Color.parseColor("#999999")) //color of cancel button
                        .colorConfirm(Color.parseColor("#333333"))//color of confirm button
                        .minYear(1900) //min year in loop
                        .maxYear(Integer.parseInt((TimeUtil.fmt.format(new Date()).toString().split("-"))[0])+1) // max year in loop
                        .showDayMonthYear(false) // shows like dd mm yyyy (default is false)
                        .dateChose(TextUtils.isEmpty(birthDay)?
                                TimeUtil.fmt.format(new Date()).toString() :birthDay) // date chose when init popwindow
                        .build();
                pickerPopWin.showPopWin(UserInfoActivity.this);
                break;
            case R.id.rl_live_place:
                openAreaDialog();
                break;
            case R.id.phone_layout: {
                mPresenter.mobile_change_state(UserDataManager.getInstance().getMobile());
            }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImg(images);

//                MyAdapter adapter = new MyAdapter(images);
//                gridView.setAdapter(adapter);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImg(images);
            }
        } else if (RESULRCODE == resultCode) {
            if (data != null) {
                Map<String, String> map = new HashMap<>();
                map.put("nick_name", data.getStringExtra("nickname"));
                mPresenter.updateUserInfo(map);
            }
        }else if(requestCode == 0x57 && resultCode == RESULT_OK) {
            String introduce = data.getStringExtra("introduce");
            if (mCustomerBean!=null &&mCustomerBean.getData()!=null) {
                mCustomerBean.getData().setIntroduce(introduce);
                tvSignature.setText(mCustomerBean.getData().getIntroduce());
                tvSignature.setTextColor(Color.parseColor("#999999"));
            } else {
                if (introduce != null) {
                    tvSignature.setText(introduce);
                }
                tvSignature.setTextColor(Color.parseColor("#999999"));
            }
        }
    }

    private void uploadImg(ArrayList<ImageItem> images) {
        List<File> files = new ArrayList<>();
        for (ImageItem item : images) {
            File imgFile = new File(item.path);
            files.add(imgFile);
        }
//                mPresenter.uploadImage(files,"customer");
        if (files.size() > 0) {
            Observable.just(files.get(0)).map(new Function<File, File>() {
                @Override
                public File apply(@NonNull File file) throws Exception {
                    return Luban.with(UserInfoActivity.this).load(file).get();
                }
            }).observeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                @Override
                public void accept(@NonNull File file) throws Exception {
                    mPresenter.uploadImage(file, "customer");
                }
            });
        }
    }

    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean) {
        Map<String, String> map = new HashMap<>();
        map.put("headimgurl", dataBean.getSh_image_url());
        mPresenter.updateUserInfo(map);
    }

    @Override
    public void onUpdateHeadImgSucccess() {
        UserDataManager.getInstance().requestCustomerInfoForceUpdate(new UserDataCallBack() {
            @Override
            public void onSuccess(CustomerBean customerBean) {
                mCustomerBean = customerBean;
                showUserInfo(customerBean);
            }
        });
        mPresenter.mRxManager.mRxBus.post("head","head");
    }

    @Override
    public void getAddressList(AddressListBean.DataBean dataBean) {
        ArrayList<City> arrayList = new ArrayList<>();
        for (AddressListBean.DataBean.ShItemsBean bean : dataBean.getSh_items()) {
            City city = new City();
            city.setGrade(mPositon);
            city.setId(bean.getSh_id());
            city.setName(bean.getSh_name());
//            city.setIsMunicipality(bean.);
            arrayList.add(city);
        }
        dialog.setCities(arrayList);
    }

    @Override
    public void mobile_change_state_result(String code, String msg) {
        if("1".equals(code)){
            ARouter.getInstance().build(FCRouterPath.USER_CHECK_MOBILE).withString("old_mobile_str",tvPhone.getText().toString().trim()).navigation();
        }else{
            showToast(msg);
        }
    }

    private void openAreaDialog() {
        dialog = new AddressSelectDialog(UserInfoActivity.this);
        dialog.setOnSelectListener(new AddressSelectDialog.OnSelectListener() {
            @Override
            public void onSelect(String position, String id, String address) {
                mPositon = position;
                mPresenter.getRegionList(id);
                if ("4".equals(position)) {
                    provinceId = id;
                    address1 = address;
                } else if ("5".equals(position)) {
                    cityId = id;
                    address2 = address;
                }else {
                    area_id = id;
                    address3 = address;
                }
            }

            @Override
            public void onSelected(String id, String name) {
                area_id = id;
                Map<String, String> map = new HashMap<>();
                map.put("city_id", cityId);
                map.put("province_id", provinceId);
                map.put("area_id", area_id);
                mPresenter.updateUserInfo(map);
                dialog.dismiss();
            }
        });
        dialog.show();
        mPresenter.getRegionList("0");
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvPhone.setText(UserDataManager.getInstance().getMobile());
    }
}
